// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs';			//const fs = require("fs");
import * as path from 'path'; //const path = require("path");
import * as stdf from './stdf/stdf';

let GOutputWindow: vscode.OutputChannel;
let GSelfPath: string;

function GForEachFileByDirectory(ADir: string, callback: (fileName: string, totalFiles: number) => void) {
	if(1){
		fs.readdir(ADir, (err, files: string[]) => {		//非阻塞
			if(err){
				GOutputWindow.appendLine("Error occurred: " + err.message);
			} else{
				files.forEach((file: string) => {
					const fullPath = path.join(ADir, file);
					if (fs.statSync(fullPath).isDirectory()) {
						GForEachFileByDirectory(fullPath, callback);
					} else {
						callback(fullPath, files.length);
					}
				});
			}
		});
	}else{	//阻塞式
		fs.readdirSync(ADir).forEach((file: string, idx: number, files: string[]) => {
		  const fullPath = path.join(ADir, file);
		  if (fs.statSync(fullPath).isDirectory()) {
		    GForEachFileByDirectory(fullPath, callback);
		  } else {
		    callback(fullPath, files.length);
		  }
		});
	}
}

function GBatchTransformToIni(AUri: vscode.Uri): void{
	const rootPath: string = AUri.fsPath;
	vscode.window.showInformationMessage("Start transform file to Ini");
	if(rootPath){
		GOutputWindow.appendLine("Open root path: " + rootPath);
		let progressOptions = {
			location: vscode.ProgressLocation.Notification,
			title: 'Transform files operation'
		};
		vscode.window.withProgress(progressOptions, (progress, token) => {
			return new Promise((resolve, reject) => {
				let filesIndex = 0;
				GForEachFileByDirectory(rootPath, (fileName, totalFiles) =>{
					GOutputWindow.appendLine(fileName);
					filesIndex++;
					progress.report({
						message: `Processing file ${filesIndex} out of ${totalFiles}: ${fileName}`,
						increment: (1 / totalFiles) * 100
					});
					if(1){	// 直接fs打开
						fs.readFile(fileName, (err, data) => {
							if(err){
								GOutputWindow.appendLine(err.message);
							} else {
								fs.writeFile(fileName + '.ini', data, (err2: any) => {
									if(err2){
										GOutputWindow.appendLine("Save error: " + fileName + '.ini');
									} else {
										GOutputWindow.appendLine("Save successfully!");
										fs.unlink(fileName, err3 =>{});
									}
								});
							}
						});
					} else{  // 先使用vscode内置文本打开， 失败后再用fs打开
						vscode.workspace.openTextDocument(fileName).then(
							(doc: vscode.TextDocument) => {
								// vscode.workspace.fs.writeFile
								fs.writeFile(fileName + '.ini', doc.getText(), (err: any) => {
									if(err){
										GOutputWindow.appendLine("Save error: " + fileName + '.ini');
									} else {
										GOutputWindow.appendLine("Save successfully!");
										fs.unlink(fileName, err =>{});
									}
								});
							},
							(reason: any) => {
								GOutputWindow.appendLine(reason + ' Reopen with binarry!');
								fs.readFile(fileName, (err, data) => {
									if(err){
										GOutputWindow.appendLine(err.message);
									} else {
										fs.writeFile(fileName + '.ini', data, (err2: any) => {
											if(err2){
												GOutputWindow.appendLine("Save error: " + fileName + '.ini');
											} else {
												GOutputWindow.appendLine("Save successfully!");
												fs.unlink(fileName, err3 =>{});
											}
										});
									}
								});
							}
						);
					}

				});
				resolve('Transform files finish');
			});
		});
		vscode.window.showInformationMessage("tools-box: finish to transfrom file!");
	} else{
		GOutputWindow.appendLine("Open root path error");
	}
}

function GOpenStdfFile(uri: vscode.Uri){
	if(uri){
		let stdfReader = new stdf.TStdfReader(uri.fsPath);
		try{
			let fromShowStdf = new stdf.TFormShowStdfFile(GSelfPath);
		} finally{
			stdfReader.close();
		}
	}
}

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
	GSelfPath = context.extensionPath;

	// Use the console to output diagnostic information (GOutputWindow.appendLine) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "tools-box" is now active!');
	GOutputWindow = vscode.window.createOutputChannel("tools-box");
	GOutputWindow.show();

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('tools-box.helloWorld', () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		//lambda function command
		vscode.window.showInformationMessage('Hello World from tools-box!');
	});

	let batchTransformToIni = vscode.commands.registerCommand("tools-box.batchTransformToIni", GBatchTransformToIni);

	let openStdfFile = vscode.commands.registerCommand("tools-box.openStdfFile", GOpenStdfFile);

	context.subscriptions.push(disposable, batchTransformToIni, openStdfFile);
}

// This method is called when your extension is deactivated
export function deactivate() {}
